from datetime import datetime

from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt.serializers import VerifyJSONWebTokenSerializer
from rest_framework.authentication import BaseAuthentication

from system import models


class TokenAuth(BaseAuthentication):
    def authenticate(self, request):
        token = {"token": None}
        # print(request.META.get("HTTP_TOKEN"))
        token["token"] = request.META.get('HTTP_AUTHORIZATION')
        valid_data = VerifyJSONWebTokenSerializer().validate(token)
        user = valid_data['user']
        if user:
            userinfo_model = models.UserInfo.objects.filter(token=token["token"], expires__gt=datetime.now()).first()
            if (userinfo_model):
                return (userinfo_model, None)
            raise AuthenticationFailed('认证失败')
        else:
            raise AuthenticationFailed('认证失败')
